//app.js
const API = require('./utils/api') //全局引入封装的网络请求
App({
  onLaunch: function () {
    //获取appid
    const accountInfo = wx.getAccountInfoSync();
    this.globalData.appid = accountInfo.miniProgram.appId
  },

  onShow:function(){
    //onLaunch全局再次打开时不会获取
    // const qrData = wx.getLaunchOptionsSync()
    // console.log('启动参数query',qrData)
    
    //2. 获取启动参数 二维码
    // if( qrData.query && qrData.query.scene ){ 
      //重置登陆状态
      // this.globalData.userInfo = {}
      // this.globalData.hasUserInfo = false

      // let query = {}
      // let scene = decodeURIComponent(qrData.query.scene).split('&')
      // scene.forEach( ele => {
      //   let key = ele.split('=')[0]
      //   query[key] = ele.split('=')[1]
      // })
      // console.log('格式化启动参数', query)
      // let globalQuery = {
      //   userId: query.uid,
      //   spreadType: query.st,
      //   type: query.t,
      // }
      // query.yqid ? globalQuery.gardenId = query.yqid : ''
      // query.qyid ? globalQuery.enterpriseId = query.qyid : ''
      // this.globalData.inviterUserId = query.uid
      // this.globalData.qrQuery = globalQuery
    // }
  },

  /**
   * 登录授权
   * 说明：获得token，已注册：返回用户信息；未登陆：返回token调用授权接口
   */
  login: function (callback) {
    let that = this
    wx.showLoading({
      title: '加载中',
    })
    wx.login({
      success(res) {
        if (res.code) {
          wx.setStorageSync('code', res.code)
          API.wx_login({
            appid: that.globalData.appid,
            code: res.code,
            inviterUserId: that.globalData.inviterUserId,  //分销绑定
          },
          that.globalData.appid).then(res => {
              // console.log( '登陆token',res )
              wx.setStorageSync('token', res.data.token)
              if( res.code == 200 && res.data.user ){ //已登录
                that.globalData.userInfo = res.data.user
                that.globalData.hasUserInfo = true
                wx.hideLoading()
                if( that.globalData.inviterUserId ){//如果通过二维码打开记录次数
                  that.creat_records('view') 
                }
                return callback(res.data.user,true) 
              }else{
                console.warn('当前账户未登录')
                that.globalData.hasUserInfo = false
                setTimeout( () => {
                  wx.hideLoading()
                },1500)
              }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
    //防止请求接口失败 一直转圈
    setTimeout( () => {
      wx.hideLoading()
    },1500)
  },

  /**
   * 获取用户信息
   */
  getUserInfo:function(callback,phoneNumber){
    // console.log('1111111111',phoneNumber,callback)
    let that = this
    //新接口，getUserInfo废弃
    wx.getUserProfile({
      lang:'zh_CN',
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('注册用于完善会员资料',res.userInfo)
        that.globalData.userInfo = res.userInfo
        that.wx_postAuth(callback,phoneNumber)
      }
    })
  },

  /**
   * 授权登陆接口 
   * 说明：创建用户
   */
  wx_postAuth:function(callback,phoneNumber){
    // console.log(this.globalData)
    let that = this
    wx.showLoading({
      title: '加载中',
    })
    console.log('wx_postAuth-----------', this.globalData.userInfo)
    let userInfo = this.globalData.userInfo
    let token = wx.getStorageSync('token')
    API.wx_postAuth({
      "city": userInfo.city,
      "country": userInfo.country,
      "headimgUrl": userInfo.avatarUrl,
      "inviterUserId": that.globalData.inviterUserId, //邀请人ID
      "nickName": userInfo.nickName,
      "token": 'wx' + token,
      "phone": "",
      "province": userInfo.province,
      "remark": "",
      "sex": "",
      "subscribeScene": "小程序",
      "wxNumber": "",
      "wxPhone": phoneNumber,
      "type": that.globalData.qrQuery.type, //来源类型
      "spreadType": that.globalData.qrQuery.spreadType
    },that.globalData.appid).then( res => {
      if( res.code == 200 ){
        that.globalData.userInfo = res.data
        that.globalData.hasUserInfo = true
        callback(res.data)
        wx.showToast({
          title: '登陆成功',
        })
        if( that.globalData.inviterUserId ){//如果通过二维码打开记录次数
          that.creat_records('view') 
        }
      }else{
        wx.showToast({
          title: '登陆失败',
          icon:'error'
        })
      }
      wx.hideLoading()
    })
  },

  /**
   * 新增日志记录
   */
  creat_records:function(type, contentType){
    let that = this
    if( type == 'poster' ){
      creat_poster_records()
    }
    else if( type == 'loanform' ){
      creat_loanform_records()
    }
    else if( type == 'share' ){
      creat_share_records()
    }
    else if( type == 'view' ){
      creat_view_records()
    }
    else{
      creat_diy_records()
    }
    function creat_poster_records(){
      API.creat_poster_records({
        userId: that.globalData.userInfo.id
      }).then()
    }
    function creat_loanform_records(){
      API.creat_loanform_records({
        userId: that.globalData.userInfo.id
      }).then()
    }
    //分享日志
    function creat_share_records(){
      API.creat_share_records({
        userId: that.globalData.userInfo.id,
        share: '1',
        type: '1'
      }).then()
    }
    //查看日志
    function creat_view_records(){
      API.creat_share_records({
        userId: that.globalData.userInfo.id,
        browses: '1',
        type: '1'
      }).then()
    }
    //自定义日志
    function creat_diy_records(){
      API.creat_diy_records({
        userId: that.globalData.userInfo.id,
        contentType: contentType
      }).then()
    }
  },

  /**
   * 联系领奖客服
   */
  contact:function(url){
    console.log('企微二维码', url)
    let urlArr = ['https://wework.qpic.cn/wwpic/471537_sKWsIUlqToy7TF6_1623999785/0'] 
    if( url ){
      urlArr = [url]
    }
    wx.previewImage({
        urls: urlArr
    })
  },

  /**
   * 统一图片上传
   */
  uploadImg:function(count, callback){
    let that = this
    wx.chooseImage({
      count: count,
      sizeType:'compressed',
      success:function(res){
        wx.showLoading({
            title: '上传中',
        })
        wx.uploadFile({
            url: API.getHost() + '/wx/appletFeedback/uploadimg', 
            header: {
                Authorization: 'wx' + wx.getStorageSync('token')
            },
            filePath: res.tempFiles[0].path,
            name: 'file',
            formData: {
                'file': res.tempFiles[0].path
            },
            success (res){
                const data = res.data
                // console.log('成功上传', JSON.parse(data).data.url)
                callback( JSON.parse(data).data.url )
                setTimeout( () => {
                    wx.hideLoading()
                },1000)
            },
            fail:function(){
                wx.hideLoading()
                wx.showToast({
                    title: '上传失败，请稍后重试',
                    icon:'none'
                })
            }
        })
      }
    })
  },

  /**
   * 统一文件上传
   */
  uploadFile:function(count, callback, extension = ['pdf']){
    let that = this
    wx.chooseMessageFile({
      type:'file',
      count: 1,
      extension:extension, //可上传格式
      success:function(res){
        wx.showLoading({
            title: '上传中',
        })
        wx.uploadFile({
            url: API.getHost() + '/common/uploadFile2Cos', 
            header: {
                Authorization: 'wx' + wx.getStorageSync('token')
            },
            filePath: res.tempFiles[0].path,
            name: 'file',
            formData: {
                'file': res.tempFiles[0].path
            },
            success (res){
                const data = res.data
                // console.log('成功上传', JSON.parse(data).url)
                callback( JSON.parse(data).url )
                setTimeout( () => {
                    wx.hideLoading()
                },1000)
            },
            fail:function(){
                wx.hideLoading()
                wx.showToast({
                    title: '上传失败，请稍后重试',
                    icon:'none'
                })
            }
        })
      }
    })
  },

  /**
   * 统一视频上传
   */
  uploadVideo:function(count, callback){
    let that = this
    wx.chooseVideo({
      sourceType: ['album','camera'],
      maxDuration: 60,
      camera: 'back',
      success:function(res){
        wx.showLoading({
            title: '上传中',
        })
        wx.uploadFile({
            url: API.getHost() + '/common/uploadFile2Cos', 
            header: {
                Authorization: 'wx' + wx.getStorageSync('token')
            },
            filePath: res.tempFilePath,
            name: 'file',
            success (res){
                const data = res.data
                // console.log('成功上传', JSON.parse(data).url)
                callback( JSON.parse(data).url )
                setTimeout( () => {
                    wx.hideLoading()
                },1000)
            },
            fail:function(){
                wx.hideLoading()
                wx.showToast({
                    title: '上传失败，请稍后重试',
                    icon:'none'
                })
            }
        })
      }
    })
  },

  globalData: {
    /**
     * 请求接口路径
     * http://192.168.0.119:8090 开发环境
     * https://miniapp.yledanpei.com 生产环境
     */
    BASE_URL: 'http://192.168.0.111:8090',
    /**
     * 腾讯地图KEY
     */
    qq_maps_key: 'DXTBZ-YDREU-SD7VG-BRWIV-ELVTV-OHF4Z',
    /**
     * 客服电话
     */
    serviceTel: '18989890356',
    appid: '',
    userInfo:'',
    hasUserInfo:true,  //是否登陆
    inviterUserId: '',  //邀请人ID
    basrUrl:'',
    qrQuery:{},  //二维码携带参数
    industry:['农、林、牧、渔业','采矿业', '制造业', '电力、燃气及水的生产和供应业', '建筑业', '交通运输、仓储和邮政业', '信息传输、计算机服务和软件业', '批发和零售业', '住宿和餐饮业', '金融业', '房地产业', '租赁和商务服务业', '科学研究、技术服务和地质勘查业', '水利、环境和公共设施管理业', '居民服务和其他服务业'],
    positionArr:['法人','股东','高管','人事','行政','普通员工'],
    measureArea: ['0-99', '100-199', '200-299', '300-499', '500-999', '1000-9999'],
  }
})